import { tauri } from "@tauri-apps/api"
import { appWindow } from "@tauri-apps/api/window";
import { on_recv } from "./service";

let initFlag = false;

const DATA_EVENT = 'SERIAL_PORT_EMIT';

export const serial_port_init = async () => {
    if (initFlag) {
        return;
    }
    initFlag = true;

    await appWindow.listen<number[]>(DATA_EVENT, (event) => {
        on_recv(event.payload);
    });
    console.log('init serial port');
}

export const active_port_name = async () => {
    return await tauri.invoke('active_port_name') as string[];
}

export const serial_port_is_open = async () => {
    return await tauri.invoke('serial_port_is_open') as boolean;
}

export const serial_port_open = async (name: string, baudRate: number = 115200) => {
    await tauri.invoke('serial_port_open', {
        name,
        baudRate
    });
}

export const serial_port_close = async () => {
    await tauri.invoke('serial_port_close');
}

export const serial_port_write = async (buf: number[]) => {
    await tauri.invoke('serial_port_write', {
        buf
    });
}

















